package zy.service.report.excel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.context.ApplicationContext;

import zy.form.PageForm;
import zy.util.DateUtil;

@SuppressWarnings("rawtypes")
public abstract class AbstractExcelReport<T> implements ReportFileInterface, ReportDataModelInterface<T> {
	@Resource
	protected ApplicationContext applicationContext;

	protected Workbook workbook;
	protected String file;
	protected FileOutputStream fileOutputStream;

	protected String time = DateUtil.getCurrentTimes();

	protected Map map;
	protected String begindate;
	protected String enddate;
	protected PageForm pageForm;
	protected Map<String, Object> sqlParameterSource;

	public void constructor(Map map) {
		this.map = map;
		initSelf();
		init(map);
	}

	protected void initSelf() {
		sqlParameterSource = new HashMap<String, Object>();
		Object _begindate = map.get("begindate");
		if (_begindate != null) {
			begindate = (String) _begindate;
			sqlParameterSource.put("begindate", begindate);
		}

		Object _enddate = map.get("enddate");
		if (_enddate != null) {
			enddate = (String) _enddate;
			sqlParameterSource.put("enddate", enddate);
		}

		Object _pageForm = map.get("pageForm");
		if (_pageForm != null) {
			pageForm = (PageForm) _pageForm;
		}
	}

	protected void init(Map map) {
	}

	@Override
	public File getFile() {
		try {
			file = setFile();
			create();
			write();
			close();
			return new File(file);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	protected String setFile() {
		String name = setFileName();
		this.file = "D:/temp/" + (name == null || name.isEmpty() ? time : name) + ".xls";
		File _file = new File(file);
		if (!_file.getParentFile().exists()) {
			_file.getParentFile().mkdirs();
		}
		return file;
	}

	protected String setFileName() {
		return null;
	}

	protected void create() throws FileNotFoundException {
		workbook = new HSSFWorkbook();
		fileOutputStream = new FileOutputStream(file);
	}

	protected abstract void write();

	protected void close() throws IOException {
		workbook.write(fileOutputStream);
		fileOutputStream.close();
		workbook.close();
	}
}